﻿/// <reference path="../classDetailsView/classDetailsView.html" />
// For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
    "use strict";
    var nav = WinJS.Navigation;
    WinJS.UI.Pages.define("/pages/departmentView/departmentView.html", {
        ready: function (element, options) {
            element.querySelector('.pagetitle').innerText = options.item.subject + ": " + options.item.subject_ldescr;

            ClassExplorer.Services.populateCourses(options.item.xml).then(function () {
                var mylist = new WinJS.Binding.List(ClassExplorer.Data.Courses.getCourses());
                var myGroupedList = mylist.createGrouped(getGroupKey, getGroupData, compareGroups);
                var listView = element.querySelector(".groupeditemslist").winControl;
                listView.itemDataSource = myGroupedList.dataSource;
                listView.groupDataSource = myGroupedList.groups.dataSource;
                listView.oniteminvoked = itemInvokedHandeler;
            });
            // Function used to sort the groups by first letter
            function compareGroups(left, right) {
                return left.toUpperCase().charCodeAt(0) - right.toUpperCase().charCodeAt(0);
            }

            // Function which returns the group key that an item belongs to
            function getGroupKey(dataItem) {
                return dataItem.catalog_nbr.toUpperCase().charAt(0);
            }

            // Function which returns the data for a group
            function getGroupData(dataItem) {
                return {
                    title: dataItem.catalog_nbr.toUpperCase().charAt(0)+"000"
                };
            }

            function itemInvokedHandeler(args) {
                var item = ClassExplorer.Data.Courses.getCourses()[args.detail.itemIndex];
                nav.navigate("/pages/classDetailsView/classDetailsView.html", { item: item });
            }

        },

        unload: function () {
            // TODO: Respond to navigations away from this page.
        },

        updateLayout: function (element, viewState, lastViewState) {
            /// <param name="element" domElement="true" />

            // TODO: Respond to changes in viewState.
        }
    });
})();
